package com.example.photo.controller;

import com.example.photo.common.BaseResponse;
import com.example.photo.common.ErrorCode;
import com.example.photo.exception.BusinessException;
import com.example.photo.utils.FileUtils;
import com.example.photo.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;

/**
 * 文件上传与查看
 *
 * @author Lwh
 * @time 2023/03/27 13:05
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    private final ServletContext servletContext;

    public FileController(ServletContext servletContext) {
        this.servletContext = servletContext;
    }


    /**
     * 上传文件
     */
    @PostMapping("/upload")
    public BaseResponse<String> upload(@RequestParam("file") MultipartFile multipartFile) {
        if (multipartFile == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String path = FileUtils.saveOriginal(multipartFile);
        if (StringUtils.isBlank(path)) {
            throw new BusinessException(ErrorCode.SERVER_ERROR, "文件保存失败");
        }
        return ResultUtils.success(path);
    }

    /**
     * 下载文件
     */
    @GetMapping("/get")
    public ResponseEntity<Resource> get(@RequestParam String path) {
        if (StringUtils.isBlank(path)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (!path.startsWith("media/")) {
            log.warn("疑似恶意的请求路径: {}", path);
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        return FileUtils.packToResponse(FileUtils.getResourceByPath(path), servletContext);
    }


//    @PostMapping("/do")
//    public BaseResponse<Map<String, Object>> doUpload(@RequestParam("file") MultipartFile imageFile) {
//        String originalPathName = saveOriginal(imageFile);
//        String thumbnailPathName = saveThumbnail(originalPathName);
//
//        Map<String, Object> map = new HashMap<>();
//        //原图地址
//        map.put("originalUrl", originalPathName);
//        //缩略图地址
//        map.put("thumbnailUrl", thumbnailPathName);
//        return ResultUtils.success(map);
//    }

    //预览图片

    //图片加水印

    //用户上传头像

    //管理员替换作品源


}
